package routes

import (
	"github.com/gin-gonic/gin"
	socketio "github.com/googollee/go-socket.io"
	"iot-base/auth/api/handler/alarm"
	"iot-base/auth/api/handler/file"
	"iot-base/auth/api/handler/ws"
	"iot-base/auth/common/socket"
	"iot-base/auth/config"
	"iot-base/auth/utils"
	"log"
)

func SocketIoRoutes(g *gin.Engine) {
	g.GET("/test", file.Test)
	g.GET("/excel", file.ExcelTest)
	InitService()
	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.OnConnect("/", ws.OnConnect)
	server.OnEvent("/", config.EventSubscribeAlarm, ws.SubscribeAlarm)
	server.OnEvent("/", config.EventUnSubscribeAlarm, ws.UnsubscribeAlarm)
	server.OnDisconnect("/", ws.OnDisconnect)
	g.GET(config.Conf.Server.Prefix+"/ws/*any", gin.WrapH(server))
	g.POST(config.Conf.Server.Prefix+"/ws/*any", gin.WrapH(server))
	utils.AntsPool.Submit(func() {
		server.Serve()
	})
}

func InitService() {
	// 启动 socket.io
	utils.AntsPool.Submit(func() {
		socket.Manager.Start()
	})
	// 订阅事件
	utils.AntsPool.Submit(func() {
		alarm.NewEvent().Run()
	})
	// 订阅告警
	utils.AntsPool.Submit(func() {
		alarm.NewAlarm().Run()
	})

}
